"""Helper to monitor certificate expiry."""
from datetime import timezone
import pathlib
import typing

from cryptography import x509
import prometheus_client

from cki_lib import misc

METRIC_CERTIFICATE_NOT_VALID_AFTER = prometheus_client.Gauge(
    'cki_certificate_not_valid_after',
    'timestamp when validity of certificate ends',
    ['path'],
)


def update_certificate_metrics(cert_path: typing.Union[pathlib.Path, str]) -> None:
    """Update metrics for the given certificate."""
    with misc.only_log_exceptions():
        if not misc.get_env_bool('CKI_METRICS_ENABLED', False):
            return
        cert = x509.load_pem_x509_certificate(pathlib.Path(cert_path).read_bytes())
        if (not_valid_after := getattr(cert, 'not_valid_after_utc', None)) is None:
            # cryptography < 42.0.0
            not_valid_after = cert.not_valid_after.replace(tzinfo=timezone.utc)
        METRIC_CERTIFICATE_NOT_VALID_AFTER.labels(cert_path).set(not_valid_after.timestamp())
